import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Input,
  Select,
  Button,
  Tag,
  Space,
  message,
  Typography,
  Popconfirm,
  Modal,
  Form,
  Switch,
} from 'antd';
import {
  SearchOutlined,
  UserOutlined,
  StopOutlined,
} from '@ant-design/icons';
import { getUsers, updateUserClass, updateUserStatus, updateUser, deleteUser } from '../../api/admin';
import { User, PageResult, USER_CLASS_MAP, USER_STATUS_MAP } from '../../types';
import { formatBytes, formatDateTime, formatShareRatio } from '../../utils/format';
import moment from 'moment';
import dayjs from 'dayjs';
import type { ColumnsType } from 'antd/es/table';
import request, { put } from '../../utils/request';

const { Search } = Input;
const { Option } = Select;
const { Title, Text } = Typography;

const UserManagement: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [keyword, setKeyword] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [form] = Form.useForm();

  const fetchUsers = async () => {
    try {
      setLoading(true);
      const response = await getUsers({
        page: currentPage,
        size: pageSize,
        keyword: keyword || undefined
      });
      if (response.data) {
        setUsers(response.data.records);
        setTotal(response.data.total);
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, [currentPage, pageSize, keyword]);

  const handleStatusChange = async (userId: number, newStatus: number) => {
    try {
      // 不允许禁用ID为1的用户
      if (userId === 1 && newStatus === 0) {
        message.error('不能禁用超级管理员账号');
        return;
      }
      
      const response = await updateUserStatus(userId, newStatus);
      if (response.code === 200) {
        message.success('状态更新成功');
        // 更新本地状态
        setUsers(users.map(user => 
          user.id === userId ? { ...user, status: newStatus } : user
        ));
      } else {
        message.error(response.message || '状态更新失败');
      }
    } catch (error) {
      console.error('更新用户状态失败:', error);
      message.error('更新用户状态失败');
    }
  };

  const handleAdminChange = async (userId: number, isAdmin: boolean) => {
    try {
      // 不允许修改ID为1的用户的管理员身份
      if (userId === 1) {
        message.error('不能修改超级管理员的管理员身份');
        return;
      }

      const response = await put<{ code: number; message: string }>(`/admin/users/${userId}/admin`, { isAdmin });
      if (response.code === 200) {
        message.success('管理员身份更新成功');
        // 更新本地状态
        setUsers(users.map(user => 
          user.id === userId ? { ...user, userClass: isAdmin ? 4 : 0 } : user
        ));
      } else {
        message.error(response.message || '管理员身份更新失败');
      }
    } catch (error) {
      console.error('更新管理员身份失败:', error);
      message.error('更新管理员身份失败');
    }
  };

  const handleDelete = async (userId: number) => {
    try {
      await deleteUser(userId);
      message.success('用户删除成功');
      fetchUsers();
    } catch (error) {
      console.error('删除用户失败:', error);
      message.error('删除用户失败');
    }
  };

  const handleEdit = (values: User) => {
    // Handle form submission
    console.log('Form values:', values);
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  const columns: ColumnsType<User> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '等级',
      dataIndex: 'userClass',
      key: 'userClass',
      render: (userClass: number) => {
        const classInfo = USER_CLASS_MAP[userClass as keyof typeof USER_CLASS_MAP];
        return classInfo ? classInfo.text : '未知';
      },
    },
    {
      title: '上传量',
      dataIndex: 'uploaded',
      key: 'uploaded',
      render: (uploaded: number) => formatBytes(uploaded),
    },
    {
      title: '下载量',
      dataIndex: 'downloaded',
      key: 'downloaded',
      render: (downloaded: number) => formatBytes(downloaded),
    },
    {
      title: '分享率',
      key: 'shareRatio',
      render: (_, record) => {
        const ratio = record.uploaded / (record.downloaded || 1);
        const ratioInfo = formatShareRatio(ratio);
        return (
          <span style={{ color: ratioInfo.color }}>
            {ratio.toFixed(2)}
          </span>
        );
      },
    },
    {
      title: '魔力值',
      dataIndex: 'bonusPoints',
      key: 'bonusPoints',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number, record: User) => (
        <Select
          value={status}
          onChange={(value) => handleStatusChange(record.id, value)}
          style={{ width: 100 }}
          disabled={record.id === 1}
        >
          <Select.Option value={1}>正常</Select.Option>
          <Select.Option value={0}>禁用</Select.Option>
        </Select>
      ),
    },
    {
      title: '管理员',
      dataIndex: 'userClass',
      key: 'userClass',
      render: (userClass: number, record: User) => (
        <Switch
          checked={userClass === 4}
          onChange={(checked) => handleAdminChange(record.id, checked)}
          disabled={record.id === 1}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: User) => (
        <Space size="middle">
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card
        title={
          <Space>
            <UserOutlined />
            <Title level={3} style={{ margin: 0 }}>用户管理</Title>
          </Space>
        }
      >
        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
          <div style={{ display: 'flex', gap: 16 }}>
            <Search
              placeholder="搜索用户名或邮箱"
              allowClear
              enterButton="搜索"
              onSearch={value => {
                setKeyword(value);
                setCurrentPage(1);
              }}
              style={{ width: 300 }}
            />
            <Button onClick={fetchUsers}>刷新</Button>
          </div>

          <Table
            columns={columns}
            dataSource={users}
            rowKey="id"
            loading={loading}
            pagination={{
              current: currentPage,
              pageSize: pageSize,
              total: total,
              onChange: (page, size) => {
                setCurrentPage(page);
                setPageSize(size);
              },
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: total => `共 ${total} 条记录`,
            }}
          />
        </Space>
      </Card>

      <Modal
        title="编辑用户"
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleEdit}
          initialValues={editingUser || undefined}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
          >
            <Select>
              <Select.Option value={1}>正常</Select.Option>
              <Select.Option value={0}>禁用</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement; 